<?php
namespace Home\Base;
/**
 * 工具类
 * @author 张云江
 * @date 2015/11/02
 */
class Util{
	/**
	 * 分页组件（聚合thinkphp分页与缓存框架分页）
	 * @param $total 总条数
	 * @param $pagesize 每页条数
	 * @param $pageindex 当前页
	 * @return array("pageshow"=>$show,"mempage"=>$mempage)，pageshow：tp分页组件，mempage：缓存分页对象
	 */
	public static function getPageObject($total,$pagesize,$pageindex=0){
		//tp分页组件设置
		$Page = new \Think\Page($total,$pagesize);
		$Page->setConfig('prev','上一页');
		$Page->setConfig('next','下一页');
		if(!empty($pageindex)){
			$Page->nowPage = $pageindex;
		}
		$show = $Page->show();
		//缓存分页设置
		$mempage = new \MemLib\PageInfo(($Page->nowPage)-1,$pagesize);
		return array("pageshow"=>$show,"mempage"=>$mempage);
	}
	
	/**
	 * 分页
	 * @param mixed $model
	 * @param mixed $where
	 * @param mixed $order
	 * @param mixed $num
	 * @return multitype:mixed string
	 */
	public static function page($model,$where,$order,$num=20){
		$count = $model->where($where)->count();
		$Page = new \Think\Page($count,$num);
		$Page->setConfig('prev','上一页');
		$Page->setConfig('next','下一页');
		$dataList = $model->where($where)->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();
		$show = $Page->show();
		$rtn = array("data"=>$dataList,"page"=>$show);
		return $rtn;
	}
	
	/**
	 * 执行查询（如果无分页则返回全部结果）
	 * @param mixed $Model
	 * @param mixed $sql_query
	 * @param mixed $order
	 * @param mixed $num
	 * @return Ambigous <multitype:string mixed , multitype:mixed string >
	 */
	public static function executeQuery($Model,$sql_query,$order,$num){
		if(empty($num)){
			$sql_data = $sql_query.$order;
			$daaList = $Model->query($sql_data);
			$rtn = $daaList;
		}else{
			$sql_count = "SELECT count(*) FROM ({$sql_query})AS TEB";
			$countObj = $Model->query($sql_count);
			$count = $countObj[0]["count(*)"];
			$Page = new \Think\Page($count,$num);
			$Page->setConfig('prev','上一页');
			$Page->setConfig('next','下一页');
			$sql_data = "{$sql_query} {$order} LIMIT ".$Page->firstRow.','.$Page->listRows;
			$daaList = $Model->query($sql_data);
			$show = $Page->show();
			$rtn = array("data"=>$daaList,"page"=>$show);
		}
		return $rtn;
	}
}